package com.novellotus.iov.carvice.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.maps.PoiOverlay;
import com.novellotus.iov.carvice.maps.SensorEventHelper;
import com.novellotus.iov.carvice.utils.MyUtils;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 充电站页面
 */
public class MapChargeStationActivity extends BaseActivity implements LocationSource,
        AMapLocationListener, PoiSearch.OnPoiSearchListener, AMap.OnInfoWindowClickListener, AMap.OnMarkerClickListener, AMap.InfoWindowAdapter, AMap.OnCameraChangeListener {


    @BindView(R.id.map)
    MapView mapView;
    @BindView(R.id.tv_tittle)
    TextView tv_tittle;
    @BindView(R.id.top)
    RelativeLayout top;
    @BindView(R.id.img_search)
    ImageView img_search;

    private AMap aMap;
    private OnLocationChangedListener mListener;
    private PoiSearch mPoiSearch;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private PoiOverlay mPoiOverlay;
    private AMapLocation mCurrentLocation;
    private String TAG = "Rich";
    private boolean mFirstFix = false;
    private Marker mLocMarker;
    private SensorEventHelper mSensorHelper;
    private PopupWindow popupWindow;
    public static final String LOCATION_MARKER_FLAG = "mylocation";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapView.onCreate(savedInstanceState);
    }

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_charge_station);
    }

    @Override
    public void init() {
        popupWindow = new PopupWindow();
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
        mSensorHelper = new SensorEventHelper(this);
        mSensorHelper.registerSensorListener();
        initLocation();
        aMap.setOnMarkerClickListener(this);
        aMap.setOnInfoWindowClickListener(this);
        aMap.setInfoWindowAdapter(this);
        aMap.setOnCameraChangeListener(this);
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                addMarkerInScreenCenter();
            }
        });
        tv_tittle.setText("一键充电");
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setRotateGesturesEnabled(false);
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
        aMap.setMinZoomLevel(4);
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
    }


    /**
     * 进行poi搜索
     *
     * @param lat
     * @param lon
     */
    private void initPoiSearch(double lat, double lon) {
        Log.e(TAG, "进行搜索");
        PoiSearch.Query poiQuery = new PoiSearch.Query("", "充电站");
        LatLonPoint centerPoint = new LatLonPoint(lat, lon);
        PoiSearch.SearchBound searchBound = new PoiSearch.SearchBound(centerPoint, 5000);
        mPoiSearch = new PoiSearch(this.getApplicationContext(), poiQuery);
        mPoiSearch.setBound(searchBound);
        mPoiSearch.setOnPoiSearchListener(this);
        mPoiSearch.searchPOIAsyn();
    }

    private void destroyLocation() {
        if (mLocationClient != null) {
            mLocationClient.unRegisterLocationListener(this);
            mLocationClient.onDestroy();
        }
    }

    /**
     * 初始化定位
     */
    private void initLocation() {
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationClient = new AMapLocationClient(this.getApplicationContext());
        mLocationClient.setLocationListener(this);
        mLocationClient.startLocation();
    }

    @OnClick(R.id.img_back)
    void back() {
        finish();
    }

    @OnClick(R.id.ibt_location)
    void clickLocation() {
        if (location != null) {
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
        }
    }

    @OnClick(R.id.img_search)
    void search() {
        openActivity(ChargeStationListActivity.class);
    }

    @OnClick(R.id.img_scan)
    void img_scan() {
        MyUtils.showToast(this,"开发中,敬请期待!");
      //  openActivity(ChargeDetailActivity.class);
    }

    @OnClick(R.id.ibt_help)
    void help() {
        AlertDialog.Builder ab=new AlertDialog.Builder(this);
        View view= LayoutInflater.from(this).inflate(R.layout.layout_charge_help,null);
        ab.setView(view);
        ab.show();
    }

    @OnClick(R.id.ibt_screen)
    void screen(){
        View view=LayoutInflater.from(this).inflate(R.layout.layout_screen_charge_station,null);
        PopupWindow popupWindow=new PopupWindow();
        popupWindow.setContentView(view);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 允许点击外部消失
        popupWindow.setBackgroundDrawable(new BitmapDrawable());//注意这里如果不设置，下面的setOutsideTouchable(true);允许点击外部消失会失效
        popupWindow.setOutsideTouchable(true);   //设置外部点击关闭ppw窗口
        popupWindow.setFocusable(true);
        popupWindow.showAsDropDown(top,0,0);
    }

    /**
     * @param latlng 自定义可以旋转的marker
     */
    private void addMarker(LatLng latlng) {
        if (mLocMarker != null) {
            return;
        }
        MarkerOptions options = new MarkerOptions();
        options.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(this.getResources(),
                R.mipmap.navi_map_gps_locked)));
        options.anchor(0.5f, 0.5f);
        options.position(latlng);
        mLocMarker = aMap.addMarker(options);
        mLocMarker.setTitle(LOCATION_MARKER_FLAG);
        mLocMarker.setClickable(false);
    }


    /**
     * 添加屏幕中心图标
     */
    private Marker locationMarker;

    private void addMarkerInScreenCenter() {
        LatLng latLng = aMap.getCameraPosition().target;
        Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
        locationMarker = aMap.addMarker(new MarkerOptions()
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.purple_pin)));
        //设置Marker在屏幕上,不跟随地图移动
        locationMarker.setClickable(false);
        locationMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
        locationMarker.setTitle("中心点");
        locationMarker.setZIndex(1);
    }


    private void show(final Marker marker) {
        View layout = View.inflate(this, R.layout.layout_charging, null);
        TextView name = layout.findViewById(R.id.tv_name);
        TextView address = layout.findViewById(R.id.tv_address);
        ImageView img_navi = layout.findViewById(R.id.img_navi);
        img_navi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startAMapNavi(marker);
            }
        });
        name.setText(marker.getTitle());
        address.setText(marker.getSnippet());
        marker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_mine_charge_choose));
        popupWindow = new PopupWindow(layout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(null, ""));
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                                             @Override
                                             public void onDismiss() {
                                                 marker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_mine_charge));
                                                 marker.setPeriod(10);
                                             }
                                         }
        );
        popupWindow.showAtLocation(top, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        if (mSensorHelper != null) {
            mSensorHelper.unRegisterSensorListener();
            mSensorHelper.setCurrentMarker(null);
            mSensorHelper = null;
        }
        deactivate();
        mFirstFix = false;
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (aMap != null) {
            aMap.clear();
            aMap = null;
        }
        mListener = null;
        mPoiSearch = null;
        mLocMarker = null;

        if (mPoiOverlay != null) {
            mPoiOverlay.clear();
            mPoiOverlay = null;
        }
        if (mSensorHelper != null) {
            mSensorHelper.unRegisterSensorListener();
            mSensorHelper = null;
        }
        mCurrentLocation = null;
        mLocationClient = null;
        mLocationOption = null;
        mPoiSearch = null;
        if (mLocMarker != null) {
            mLocMarker.destroy();
        }
        popupWindow = null;
        destroyLocation();
        mapView = null;
    }

    LatLng location;

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                location = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                if (!mFirstFix) {
                    mFirstFix = true;
                    addMarker(location);//添加定位图标
                    mSensorHelper.setCurrentMarker(mLocMarker);//定位图标旋转
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 10));
                } else {
                    mLocMarker.setPosition(location);

                    //   aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
                }
                mCurrentLocation = amapLocation;
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mLocationClient == null) {
            mLocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            mLocationOption.setInterval(20000);//隔20秒
            //设置定位监听
            mLocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            //  mLocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(final Marker marker) {
        return null;
    }


    private void startAMapNavi(Marker marker) {
        if (mLocationOption == null) {
            MyUtils.logInformation("mCurrentLocation空");
            return;
        }
        Intent intent = new Intent(MapChargeStationActivity.this, RouteNaviActivity.class);
        intent.putExtra("gps", false);
        intent.putExtra("start", new NaviLatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()));
        intent.putExtra("end", new NaviLatLng(marker.getPosition().latitude, marker.getPosition().longitude));
        startActivity(intent);
    }

    @Override
    public void onInfoWindowClick(Marker marker) {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        if (!marker.getTitle().equals("中心点")) {
            show(marker);
        }
        return false;
    }


    /**
     * @param poiResult
     * @param i         搜索成功回调
     */
    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        if (i != AMapException.CODE_AMAP_SUCCESS || poiResult == null) {
            return;
        }
        if (mPoiOverlay != null) {
            mPoiOverlay.addClusterToMap(poiResult.getPois());
        } else {
            mPoiOverlay = new PoiOverlay(aMap, poiResult.getPois());
        }

    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {


    }

    private long searchTime = 0;

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        long secondTime = System.currentTimeMillis();
        if (!popupWindow.isShowing() && secondTime - searchTime > 1000) {
            searchTime = System.currentTimeMillis();
            initPoiSearch(cameraPosition.target.latitude, cameraPosition.target.longitude);
        }
    }


}
